<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
  class UserBridgeController extends AppController
  {
      //var $uses = array();
      private $renderFile = "bridge_output";
      function beforeFilter() {
          //authenticate by token
          parent::beforeFilter();
      }
      /**
       * Returns token for authentication.
       * Registers users if not persent.
       * json input :
       *  same as registration
       *   
       */
      function login()
      {
          $data = $_POST;
          $remoteUserId = $data['id'];
          if($this->UserBridge->isRegistered($remoteUserId) == false)
          {
              $registerResult =$this->UserBridge->register($data);
              if($registerResult !== true)
              {
                  $this->set("result",false);
                  $this->set("error",$registerResult);
                  return;
              }
          }
          $this->set("result",true);
          $loginToken = $this->UserBridge->getLoginToken($remoteUserId);
          $this->set("data",array("loginToken"=>$loginToken));
      }
      
      /**
       *Register user
       * input :
       *  id,
       *  email,
       *  username,
       *  registration_date,
       *  otherInformation  : {}
       * 
       */
      function register()
      {
          $data = $_POST;
          $remoteUserId = $data['id'];
          if($this->UserBridge->isRegistered($remoteUserId) == false)
          {
              $saved = $this->UserBridge->register($data);
              if($saved !== true)
              {
                  $this->set("error",$saved);
                  $this->set("result",false);
              }else
              {
                  $this->set("result",true);
              }
          }else 
          {
              //$this->UserBridge->updateUser($data);
              $this->set("result",true);
          }
      }
      
      function render($action = null, $layout = null, $file = null) {
          $action = $this->renderFile;
          return parent::render($action, $layout, $file);
      }
      /**
       * Delete user. 
       */
      function delete()
      {
          
      }
      
      function dispatchMethod($method, $params = array()) {
          if(!cr("BridgeConfig"))
          {
              cri("Bride.BridgeConfig")->init();
          }
          if(!isset($_SERVER['HTTP_X_BRIDGE_TOKEN']) || !cr("BridgeConfig.token") || $_SERVER['HTTP_X_BRIDGE_TOKEN'] != cr("BridgeConfig.token"))
          {
               $this->set("error",array("Invalid access token"));
               $this->set("result",false);
               return;
          }
         // $authToken = 
          parent::dispatchMethod($method, $params);
      }
  }
?>
